package net.anzhuo.common.advice;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import net.anzhuo.common.entity.ResultVO;
import net.anzhuo.common.enums.ResultEnum;
import net.anzhuo.common.exception.AppException;
import net.anzhuo.common.utils.ResponseUtil;

@Component
public class ExceptionResolver implements HandlerExceptionResolver {
	
	private static final Logger log = LoggerFactory.getLogger(ExceptionResolver.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {		
		ex.printStackTrace();
		log.error("===>"+ex);
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		ResponseBody responseBody = AnnotationUtils.findAnnotation(method, ResponseBody.class);
		if (responseBody != null) {
			if (ex instanceof AppException) {
				ResultVO resultVO = new ResultVO();
				resultVO.setCode(((AppException) ex).getCode());
				resultVO.setMsg(ex.getMessage());
				ResponseUtil.responseJson(response, 400, resultVO);
			} else {
				ResultVO resultVO = new ResultVO();
				resultVO.setCode(((AppException) ex).getCode());
				resultVO.setMsg(ex.getMessage());
				ResponseUtil.responseJson(response, 500, resultVO);
			}
			return new ModelAndView();
		}

		ModelAndView modelAndView = new ModelAndView();
		if (ex instanceof AppException) {
			modelAndView.addObject("msg", ex.getMessage());
			modelAndView.setStatus(HttpStatus.BAD_REQUEST);
		} else {
			modelAndView.addObject("msg", ResultEnum.SYSTEM_ERROR.getMessage());
			modelAndView.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
		}
		modelAndView.setViewName("/error");
		return modelAndView;
	}
}
